import csv

from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth import get_user_model

from django import forms
from bases.models import Progress
from .models import Project, ProgressReport
from notifications.models import Notification

def progress_list(request):
    progresses = Progress.objects.all()
    return render(request, 'progress_tracking/progress_list.html', {'progresses': progresses})

def progress_detail(request, pk):
    progress = get_object_or_404(Progress, pk=pk)
    return render(request, 'progress_tracking/progress_detail.html', {'progress': progress})
# progress_tracking/views.py

from django.shortcuts import render, get_object_or_404, redirect
from .models import Project
from django.forms import ModelForm

# 表单类
class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = ['title', 'description', 'start_date', 'end_date', 'completed']
        labels = {
            'title': '项目名称',
            'description': '描述',
            'start_date': '开始日期',
            'end_date': '截止日期',
            'completed': '是否完成'
        }

# 列表
def project_list(request):
    projects = Project.objects.all()
    return render(request, 'progress_tracking/project_list.html', {'projects': projects})

# 新增
def project_create(request):
    form = ProjectForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('project_list')
    return render(request, 'progress_tracking/project_form.html', {'form': form, 'title': '新增项目'})

# 编辑
def project_update(request, pk):
    project = get_object_or_404(Project, pk=pk)
    form = ProjectForm(request.POST or None, instance=project)
    if form.is_valid():
        form.save()
        return redirect('project_list')
    return render(request, 'progress_tracking/project_form.html', {'form': form, 'title': '编辑项目'})

# 删除
def project_delete(request, pk):
    project = get_object_or_404(Project, pk=pk)
    if request.method == 'POST':
        project.delete()
        return redirect('project_list')
    return render(request, 'progress_tracking/project_confirm_delete.html', {'object': project})


# 查询

def project_list(request):
    query_title = request.GET.get('title', '')
    query_completed = request.GET.get('completed', '')

    projects = Project.objects.all()

    if query_title:
        projects = projects.filter(title__icontains=query_title)

    if query_completed in ['True', 'False']:
        projects = projects.filter(completed=(query_completed == 'True'))

    return render(request, 'progress_tracking/project_list.html', {
        'projects': projects,
        'query_title': query_title,
        'query_completed': query_completed
    })
def set_deadline(request, pk):
    project = get_object_or_404(Project, pk=pk)
    if request.method == 'POST':
        new_end_date = request.POST.get('end_date')
        project.end_date = new_end_date
        project.save()
        return redirect('project_list')
    return render(request, 'progress_tracking/set_deadline.html', {'project': project})
def clean_invalid_data(request):
    if request.method == 'POST':
        # 示例：删除所有 completed=False 且创建时间超过一周的记录
        from django.utils import timezone
        one_week_ago = timezone.now() - timezone.timedelta(weeks=1)
        Progress.objects.filter(completed=False, created_at__lt=one_week_ago).delete()
        return redirect('progress_list')
    return render(request, 'progress_tracking/clean_invalid_data.html')


# views.py
from notifications.models import Notification
from django.contrib.auth.models import User


def extend_deadline(request, pk):
    project = get_object_or_404(Project, pk=pk)

    if request.method == 'POST':
        new_end_date = request.POST.get('end_date')
        project.end_date = new_end_date
        project.save()

        # 获取学生和教师用户（根据 Profile 判断）
        User = get_user_model()

        # 方法一：使用 Profile 关联表查询（假设你用了 OneToOneField）
        students = User.objects.filter(student_profile__isnull=False)
        teachers = User.objects.filter(teacher_profile__isnull=False)

        recipients = list(students) + list(teachers)

        # 创建通知
        notification = Notification.objects.create(
            title=f"项目 {project.title} 截止时间已延长",
            message=f"项目 {project.title} 的截止时间已延长至 {new_end_date}，请尽快提交。",
        )
        notification.users.set(recipients)
        notification.save()

        return redirect('project_list')

    return render(request, 'progress_tracking/extend_deadline.html', {'project': project})


def unsubmitted_projects_report(request):
    projects = Project.objects.filter(completed=False)
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="unsubmitted_projects.csv"'

    writer = csv.writer(response)
    writer.writerow(['项目名称', '开始日期', '截止日期', '状态'])

    for project in projects:
        progresses = Progress.objects.filter(project=project)
        if not progresses.exists() or not all(p.completed for p in progresses):
            writer.writerow([project.title, project.start_date, project.end_date, '未完成'])

    return response
def export_projects_csv(request):
    # 获取所有项目数据
    projects = Project.objects.all()

    # 创建响应对象，设置 Content-Type 和文件名
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="projects_report.csv"'

    writer = csv.writer(response)
    # 写入表头
    writer.writerow([
        '项目名称', '描述', '开始日期', '截止日期', '是否完成'
    ])

    # 写入数据行
    for project in projects:
        writer.writerow([
            project.title,
            project.description,
            project.start_date,
            project.end_date,
            '已完成' if project.completed else '进行中',
        ])

    return response

class ProgressForm(forms.ModelForm):
    class Meta:
        model = ProgressReport
        fields = ['title', 'content', 'file']
        labels = {
            'title': '进度标题',
            'content': '进度内容',
            'file': '上传附件（可选）'
        }

def submit_progress(request):
    # 获取学生自己的课题
    project = Project.objects.filter(students=request.user).first()

    if not project:
        return render(request, 'student/topics.html', {
            'project': None
        })

    if request.method == 'POST':
        form = ProgressForm(request.POST, request.FILES)
        if form.is_valid():
            report = form.save(commit=False)
            report.project = project
            report.student = request.user
            report.save()
            return redirect('student_dashboard')
    else:
        form = ProgressForm()

    return render(request, 'student/topics.html', {
        'project': project,
        'form': form
    })


def student_progress_success(request):
    return render(request, 'progress_tracking/student_progress_success.html')